﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using KSOAdmin.Core;
using KSOAdmin.Core.CacheHelper.Interface;
using KSOAdmin.Core.EFDbContext;
using KSOAdmin.IRepository;
using KSOAdmin.IRepository.System;
using KSOAdmin.IServices.System;
using KSOAdmin.Models.DomainModels.System;

namespace KSOAdmin.Services.System
{
    public class Sys_ProvinceServices : BasicServices<Sys_Province>, ISys_ProvinceServices, IDependency
    {
        private readonly ISys_ProvinceRepository _pository;
        private readonly IBasicRepository<Sys_Province> _BaseRepository;
        private readonly ICacheService _RedisService;
        public Sys_ProvinceServices(ISys_ProvinceRepository pository, IBasicRepository<Sys_Province> BaseRepository, ICacheService redisService)
        {
            this._pository = pository;
            this.repository = BaseRepository;//父类
            this._BaseRepository = BaseRepository;
            this._RedisService = redisService;
        }

        public async Task<List<Dictionary<string, object>>> RegionList()
        {
            List<Sys_Province> regionList = new();
            if (_RedisService.Exists("KSORegions", Core.CacheHelper.CacheDataType.DateOther))
            {
                regionList = _RedisService.Get<List<Sys_Province>>("KSORegions", Core.CacheHelper.CacheDataType.DateOther);
            }
            else
            {
                regionList = await GetAll();
#pragma warning disable CS4014 // 由于此调用不会等待，因此在调用完成前将继续执行当前方法
                Task.Factory.StartNew(() => {
                    _RedisService.AddObject("KSORegions", Core.CacheHelper.CacheDataType.DateOther, regionList, 60*60*24*10);
                });
#pragma warning restore CS4014 // 由于此调用不会等待，因此在调用完成前将继续执行当前方法
            }
            return GetMultistage(null, regionList);
        }

        private async Task<List<Sys_Province>> GetAll()
        {
            List<Sys_Province> task = await  _pository.FindListAsync(w => true);
            return task;
        }
        private List<Dictionary<string, object>> GetMultistage(int? id, List<Sys_Province> ProvincesAll)
        {
            var Provinces = id == null
               ? ProvincesAll.Where(w => w.pid ==1).ToList()
               : ProvincesAll.Where(w => w.pid == id).ToList();
            if (Provinces==null ||Provinces.Count==0)
            {
                return null;
            }
            var sytu = Provinces.Select(item => new Dictionary<string, object>
            {
                ["value"] = item.Sys_Provincename,
                ["label"] = item.Sys_Provincename,
                ["children"] = this.GetMultistage(item.id, ProvincesAll)
            })
                .ToList();
            return sytu;
        }



    }
}
